/**
 * 工具函数库
 * 提供各种实用的辅助函数
 */

const Utils = {
  
  /**
   * 生成唯一ID
   */
  generateId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
  },
  
  /**
   * 格式化时间戳
   */
  formatTime(timestamp, showDate = false) {
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    
    // 小于1分钟显示"刚刚"
    if (diff < 60000) {
      return '刚刚';
    }
    
    // 小于1小时显示"X分钟前"
    if (diff < 3600000) {
      const minutes = Math.floor(diff / 60000);
      return `${minutes}分钟前`;
    }
    
    // 同一天显示时间
    if (date.toDateString() === now.toDateString()) {
      return date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      });
    }
    
    // 显示日期和时间
    if (showDate) {
      return date.toLocaleString('zh-CN', {
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    }
    
    return date.toLocaleDateString('zh-CN');
  },
  
  /**
   * 转义HTML字符
   */
  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  },
  
  /**
   * 解析URL
   */
  parseUrls(text) {
    const urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, '<a href="$1" target="_blank" rel="noopener">$1</a>');
  },
  
  /**
   * 验证昵称
   */
  validateNickname(nickname) {
    const config = CONFIG.user.nickname;
    
    if (!nickname || typeof nickname !== 'string') {
      return { valid: false, error: '昵称不能为空' };
    }
    
    if (nickname.length < config.minLength) {
      return { valid: false, error: `昵称不能少于${config.minLength}个字符` };
    }
    
    if (nickname.length > config.maxLength) {
      return { valid: false, error: `昵称不能超过${config.maxLength}个字符` };
    }
    
    if (!config.pattern.test(nickname)) {
      return { valid: false, error: '昵称只能包含字母、数字、中文、下划线和横线' };
    }
    
    const lowerNickname = nickname.toLowerCase();
    for (const word of config.forbiddenWords) {
      if (lowerNickname.includes(word.toLowerCase())) {
        return { valid: false, error: '昵称包含敏感词汇' };
      }
    }
    
    return { valid: true };
  },
  
  /**
   * 本地存储操作
   */
  storage: {
    get(key, defaultValue = null) {
      try {
        const item = localStorage.getItem(key);
        return item ? JSON.parse(item) : defaultValue;
      } catch (error) {
        console.warn('获取本地存储失败:', error);
        return defaultValue;
      }
    },
    
    set(key, value) {
      try {
        localStorage.setItem(key, JSON.stringify(value));
        return true;
      } catch (error) {
        console.warn('设置本地存储失败:', error);
        return false;
      }
    },
    
    remove(key) {
      try {
        localStorage.removeItem(key);
        return true;
      } catch (error) {
        console.warn('删除本地存储失败:', error);
        return false;
      }
    },
    
    clear() {
      try {
        localStorage.clear();
        return true;
      } catch (error) {
        console.warn('清空本地存储失败:', error);
        return false;
      }
    }
  },
  
  /**
   * 防抖函数
   */
  debounce(func, wait, immediate = false) {
    let timeout;
    return function executedFunction(...args) {
      const later = () => {
        timeout = null;
        if (!immediate) func(...args);
      };
      const callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) func(...args);
    };
  },
  
  /**
   * 节流函数
   */
  throttle(func, limit) {
    let inThrottle;
    return function(...args) {
      if (!inThrottle) {
        func.apply(this, args);
        inThrottle = true;
        setTimeout(() => inThrottle = false, limit);
      }
    };
  },
  
  /**
   * 深拷贝对象
   */
  deepClone(obj) {
    if (obj === null || typeof obj !== 'object') return obj;
    if (obj instanceof Date) return new Date(obj.getTime());
    if (obj instanceof Array) return obj.map(item => this.deepClone(item));
    if (typeof obj === 'object') {
      const copy = {};
      Object.keys(obj).forEach(key => {
        copy[key] = this.deepClone(obj[key]);
      });
      return copy;
    }
  },
  
  /**
   * 检测设备类型
   */
  device: {
    isMobile() {
      return /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    },
    
    isTouch() {
      return 'ontouchstart' in window || navigator.maxTouchPoints > 0;
    },
    
    getOS() {
      const userAgent = navigator.userAgent;
      if (/Windows/i.test(userAgent)) return 'Windows';
      if (/Mac/i.test(userAgent)) return 'Mac';
      if (/Linux/i.test(userAgent)) return 'Linux';
      if (/Android/i.test(userAgent)) return 'Android';
      if (/iPhone|iPad|iPod/i.test(userAgent)) return 'iOS';
      return 'Unknown';
    }
  },
  
  /**
   * 网络状态检测
   */
  network: {
    isOnline() {
      return navigator.onLine;
    },
    
    onStatusChange(callback) {
      window.addEventListener('online', () => callback(true));
      window.addEventListener('offline', () => callback(false));
    }
  },
  
  /**
   * 通知权限和显示
   */
  notification: {
    async requestPermission() {
      if (!('Notification' in window)) {
        return 'not-supported';
      }
      
      if (Notification.permission === 'granted') {
        return 'granted';
      }
      
      if (Notification.permission === 'denied') {
        return 'denied';
      }
      
      const permission = await Notification.requestPermission();
      return permission;
    },
    
    show(title, options = {}) {
      if (Notification.permission === 'granted') {
        return new Notification(title, {
          icon: '/favicon.ico',
          badge: '/favicon.ico',
          ...options
        });
      }
      return null;
    }
  },
  
  /**
   * 音频播放
   */
  audio: {
    playNotification() {
      if (!CONFIG.ui.notifications.sound) return;
      
      // 创建音频上下文（Web Audio API）
      try {
        const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
        const oscillator = audioCtx.createOscillator();
        const gainNode = audioCtx.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(audioCtx.destination);
        
        oscillator.frequency.value = 800;
        oscillator.type = 'sine';
        gainNode.gain.setValueAtTime(0.3, audioCtx.currentTime);
        gainNode.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.5);
        
        oscillator.start(audioCtx.currentTime);
        oscillator.stop(audioCtx.currentTime + 0.5);
      } catch (error) {
        console.warn('播放通知声音失败:', error);
      }
    }
  },
  
  /**
   * DOM 操作工具
   */
  dom: {
    $(selector) {
      return document.querySelector(selector);
    },
    
    $$(selector) {
      return document.querySelectorAll(selector);
    },
    
    create(tag, props = {}, children = []) {
      const element = document.createElement(tag);
      
      Object.keys(props).forEach(key => {
        if (key === 'className') {
          element.className = props[key];
        } else if (key.startsWith('on')) {
          element.addEventListener(key.slice(2).toLowerCase(), props[key]);
        } else {
          element.setAttribute(key, props[key]);
        }
      });
      
      children.forEach(child => {
        if (typeof child === 'string') {
          element.appendChild(document.createTextNode(child));
        } else {
          element.appendChild(child);
        }
      });
      
      return element;
    },
    
    scrollToBottom(element, smooth = true) {
      element.scrollTo({
        top: element.scrollHeight,
        behavior: smooth ? 'smooth' : 'auto'
      });
    },
    
    isScrolledToBottom(element, threshold = 50) {
      return element.scrollHeight - element.scrollTop - element.clientHeight < threshold;
    }
  },
  
  /**
   * 错误处理
   */
  error: {
    log(error, context = '') {
      if (CONFIG.debug.enabled) {
        console.error(`[${context}]`, error);
      }
    },
    
    notify(message, type = 'error') {
      // 这将在 UI.js 中实现
      if (window.UI && window.UI.showNotification) {
        window.UI.showNotification(message, type);
      }
    }
  },
  
  /**
   * 速率限制器
   */
  rateLimiter: {
    limits: new Map(),
    
    check(key, maxCount, timeWindow) {
      const now = Date.now();
      
      if (!this.limits.has(key)) {
        this.limits.set(key, []);
      }
      
      const timestamps = this.limits.get(key);
      
      // 清理过期的时间戳
      while (timestamps.length > 0 && timestamps[0] < now - timeWindow) {
        timestamps.shift();
      }
      
      // 检查是否超过限制
      if (timestamps.length >= maxCount) {
        return false;
      }
      
      // 记录当前时间戳
      timestamps.push(now);
      return true;
    },
    
    reset(key) {
      this.limits.delete(key);
    },
    
    clear() {
      this.limits.clear();
    }
  }
};

// 导出工具函数
if (typeof module !== 'undefined' && module.exports) {
  module.exports = Utils;
}